package com.example.webpractice.controller;

import com.example.webpractice.annotation.IgnoreAuth;
import com.example.webpractice.dto.Calc2DTO;
import com.example.webpractice.service.CalcService;
import com.example.webpractice.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/calc")
public class Calccontroller {
    public List<String> ops = List.of("+", "-", "*", "/", "min", "max", "pow");
    @Autowired
    private CalcService calcService;

    @IgnoreAuth
    @RequestMapping("/cal1")
    public Result cal1(@RequestParam(name = "num1") Integer a,
                       @RequestParam(name = "num2") Integer b,
                       @RequestParam(name = "op", required = false) String op) {
        Result r = new Result();

        if (op == null) {
            op = "+";
        }
        if (!ops.stream().anyMatch(op::equals)) {
            r.setCode(-3);
            r.setErrMsg("操作符号不支持");
            return r;
        }
        int c = calcService.Calc(a, b, op);
        r.setCode(0);
        r.setResult(c);
        return r;
    }

    @IgnoreAuth
    @RequestMapping("/cal2")
    public Result cal2(@RequestBody Calc2DTO dto) {
        if (dto.getNum1() == null || dto.getNum2() == null) {
            return new Result(-3, "a,b均不能是空", 0);
        }
        String op = dto.getOp();
        if (op == null) {
            op = "+";
        }
        Result r = new Result();
        int c = calcService.Calc(dto.getNum1(), dto.getNum2(), op);
        r.setCode(0);
        r.setResult(c);
        return r;
    }
}
